package com.wanmait.studentmangers.dao;
import com.wanmait.studentmangers.util.DBHelper;
import com.wanmait.studentmangers.vo.Userinfo;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UserinfoDaoImpl implements UserinfoDao {

    @Override
    public void insert(Userinfo userinfo) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        conn = DBHelper.getConnection();

        String sql = "insert into userinfo(username,userpass) values(?,?)";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userinfo.getUsername());
            pstmt.setString(2,userinfo.getUserpass());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBHelper.close(conn, pstmt, null);
        }
    }
    public boolean login(Userinfo userinfo) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean flag = false;
        conn = DBHelper.getConnection();
        String sql = "select * from userinfo where username=? and userpass=?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userinfo.getUsername());
            pstmt.setString(2, userinfo.getUserpass());
             rs = pstmt.executeQuery();
         if(rs.next()) {
             return !flag;
         }
         return flag;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Userinfo> getAll() {
        List<Userinfo> list = new ArrayList<Userinfo>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        conn = DBHelper.getConnection();
        String sql = "select * from userinfo";
     try {
     pstmt = conn.prepareStatement(sql);
     rs = pstmt.executeQuery();
     while(rs.next()) {
         Userinfo userinfo = new Userinfo();
         userinfo.setId(rs.getInt("id"));
         userinfo.setUsername(rs.getString("username"));
         userinfo.setUserpass(rs.getString("userpass"));
         list.add(userinfo);
     }

     }catch (SQLException e) {
     throw new RuntimeException(e);
     }finally {
         DBHelper.close(conn, pstmt, rs);
     }
     return list;
    }

    @Override
    public void add(Userinfo userinfo) {

    }

    @Override
    public List<Userinfo> getList() {
        return null;
    }


}
